/*{
单元名称：菜单页导航behavior
单元功能：点击菜单操作
所属模块功能：
创建人：yan
创建时间：230901
修改人：
修改时间：
}*/

import {GetUrlString} from "../utils/utils";

module.exports = Behavior({
  data: {
    navList: []
  },
  methods: {
    wxScanCode(){
      return new Promise(resolve => {
        // resolve('202308211103115073035251');
        let {orderid} = this.data;
        if (orderid){
          resolve(orderid);
          //清除orderid参数
          this.setData({orderid: ''});
          return;
        }
        wx.scanCode({
          success: async (res) => {
            if (res.errMsg === "scanCode:ok") {
              console.log("扫码结果");
              console.log(res);
              let {result} = res,
                orderid = result;
              if (result.indexOf('http://yfgpwebapi.fszyrj.com/wlxcx/') >= 0){
                let obj = {};
                /* for (let i = 1;i<8;i++){
                  let item = 'param' + i
                  obj[item] = GetUrlString(result,item);
                }
                console.log(obj);
                orderid = obj.param4 || ''*/
                let dm =  wx.$util.GetUrlString(result,'dm');
                if (dm){
                  await this.getShortSource(dm).then(res => {
                    if (res) {
                      let arr = res.split('&');
                      arr.forEach(item => {
                        let kv = item.split('=');
                        obj[kv[0]] = kv[1]
                      });
                    }
                  })
                } else {
                  for (let i = 1;i<8;i++){
                    let item = 'param' + i
                    obj[item] =  wx.$util.GetUrlString(result,item);
                  }
                }
                orderid = obj.param4 || ''
              }
              resolve(orderid);
            }
          },
          fail: (res) => {
            console.log(res);
            wx.$toast('扫码失败')
            resolve();
          }
        })
      })
    },
    navigator(e){
      let {isScan,url} = e.currentTarget.dataset.opt;
      if (isScan){
        this.wxScanCode().then(res => {
          wx.navigateTo({
            url: `${url}?orderid=${res || ''}`
          })
        })
      }else {
        wx.navigateTo({
          url: url
        })
      }
    },

    //  短码换取二维码参数
    getShortSource(code){
      return new Promise(resolve => {
        let url = 'WL/Get_short_to_Source'
        wx.$get(5,url,{data_in: code}).then(res => {
          if (res.errcode != 0) {
            resolve()
            return;
          }
          let code = res.data.row[0] && res.data.row[0].yuanma
          resolve(code)
        })
      })
    },
  }
})
